package Ep06_BinaryTree.BT12_0110;

import Ep06_BinaryTree.TreeNode;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/5/4 19:22
 * 说明：使用后序遍历求高度，因为需要在树底将高度一层一层向上return
 * 如果是求深度的话使用先序遍历，因为从root开始就要将深度一层一层向下累加
 */

public class Best {
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }
    public int getHeight(TreeNode root){
        if (root == null) return 0;
        int leftH = getHeight(root.left);
        if (leftH == -1) return -1;
        int rightH = getHeight(root.right);
        if (rightH == -1) return -1;
        int result;
        if (Math.abs(rightH - leftH) > 1){
            result = -1;
        } else {
            result = 1 + Math.max(leftH, rightH);
        }
        return result;
    }
}
